package com.dunmin.concurrency.sync;

/**
 * Created by Administrator on 2018/4/28.
 */
public class SynchronizedDemo {

    private boolean ready = false;
    private int result = 0;
    private int number = 1;

    /**
     * 写操作
     */
    public void write(){
        ready = true;
        number = 2;
    }

    /**
     * 读操作
     */
    public void read(){
        if(ready){              // 2.1
            result = number * 3;// 2.2
        }
        System.out.println("result的值为:" + result);
    }

    /**
     * 内部线程类
     */
    private class ReadWriteThread extends Thread{
        private boolean flag;
        public ReadWriteThread(boolean flag){
            this.flag = flag;
        }

        @Override
        public void run(){
            if(flag){
                // 构造方法传入true，执行写操作
                write();
            }else{
                // 构造方法传入false，执行读操作
                read();
            }
        }
    }

    public static void main(String[] args) {
        // 在主线程中启动线程执行读写操作
        SynchronizedDemo synchronizedDemo = new SynchronizedDemo();
        // 启动线程执行写操作
        synchronizedDemo.new ReadWriteThread(true).start();
        try {
            Thread.sleep(1000);// 休眠1秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 启动线程执行读操作
        synchronizedDemo.new ReadWriteThread(false).start();

        // 假设写线程启动后,马上就获取到了cpu的执行权


    }

}
